<template>
  <div class="relative leading-[0]">
    <input
      v-if="props.type == TYPE_TEXT"
      class="border-gray-200 dark:border-zinc-600 dark:bg-zinc-800 duration-100 dark:text-zinc-400 border-[1px] outline-0 py-0.5 px-1 text-sm rounded-sm focus:border-blue-400 w-full"
      type="text"
      v-model="text"
      :maxlength="props.maxlength"
    />
    <textarea
      v-if="props.type == TYPE_TEXTAREA"
      v-model="text"
      :maxlength="props.maxlength"
      rows="5"
      class="border-gray-200 dark:border-zinc-600 dark:bg-zinc-800 duration-100 dark:text-zinc-400 border-[1px] outline-0 py-0.5 px-1 text-sm rounded-sm focus:border-blue-400 w-full"
    />
    <span
      v-if="props.maxlength"
      class="absolute right-1 bottom-0.5 text-zinc-400 text-xs"
      :class="{ 'text-red-700': currentLength === parseInt(props.maxlength) }"
      >{{ currentLength }} / {{ props.maxlength }}</span
    >
  </div>
</template>

<script>
const TYPE_TEXT = 'text'
const TYPE_TEXTAREA = 'textarea'
</script>
<script setup>
import { ref, reactive, toRefs, onMounted, computed } from 'vue'
import { useVModel } from '@vueuse/core'
const emits = defineEmits(['update:modelValue'])

const props = defineProps({
  // 双向数据绑定
  modelValue: {
    type: String,
    required: true
  },
  // 类型
  type: {
    type: String,
    default: TYPE_TEXT,
    validator: (value) => {
      const res = [TYPE_TEXT, TYPE_TEXTAREA].includes(value)
      if (!res) {
        throw new Error(
          `type属性的值只能是${[TYPE_TEXT, TYPE_TEXTAREA].join('、')}中的一个`
        )
      }
      return res
    }
  },
  // 最大输入数
  maxlength: { type: [String, Number] }
})
const text = useVModel(props)

// 计算当前传入的输入长度
const currentLength = computed(() => text.value.length)
</script>
<style scoped lang="scss"></style>
